#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "auth.h"

char* ak = "API Key";
char* sk = "Secret Key";

int tts(char* token, char* text)
{
    FILE* fp = fopen("tts.pcm", "w+");
    if (!fp)
    {
        perror("fopen");
        return 1;
    }

    CURL* client = curl_easy_init();

    //发送到API的字符串需要进行2次URL编码
    char* encoded1 = curl_easy_escape(client, text, 0);
    printf("%s\n", encoded1);
    char* encoded2 = curl_easy_escape(client, encoded1, 0);
    free(encoded1);

    //准备POST参数
    char* postdata = NULL;
    asprintf(&postdata, "tex=%s&lan=zh&cuid=liuyu&ctp=1&aue=4&per=1&tok=%s", encoded2, token);
    free(encoded2);

    curl_easy_setopt(client, CURLOPT_URL, "https://tsn.baidu.com/text2audio");
    curl_easy_setopt(client, CURLOPT_POST, 1);
    curl_easy_setopt(client, CURLOPT_POSTFIELDS, postdata);
    curl_easy_setopt(client, CURLOPT_WRITEDATA, fp);

    //发送请求消息
    CURLcode error = curl_easy_perform(client);
    if (error != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform: %s\n", curl_easy_strerror(error));
        free(postdata);
        fclose(fp);
        curl_easy_cleanup(client);
        return 1;
    }

    fclose(fp);

    char* ct = NULL;
    curl_easy_getinfo(client, CURLINFO_CONTENT_TYPE, &ct);
    //判断返回结果，如果不是音频文件则出错
    if (strncmp(ct, "audio", 5) != 0)
    {
        fprintf(stderr, "API call failed\n");
    }

    free(postdata);
    curl_easy_cleanup(client);

    return 0;
}

int main()
{
    char* token = get_token(ak, sk);
    if (!token)
    {
        return EXIT_FAILURE;
    }

    char line[120];

    while (fgets(line, sizeof line, stdin))
    {
        tts(token, line);
        //play audio
    }

    return EXIT_SUCCESS;
}